//网站
querybrandWebsites()
function querybrandWebsites() {
    $.ajax({
        type: "POST",
        url: root.brandWebsite.query,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({

        }),
        success: function (data) {
            for (var i=0;i<data.data.data.length;i++){
                $("#websiteId").append("<option value=" + data.data.data[i].id + " >" + data.data.data[i].websiteName + "</option>")
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//一级分类
categoryIds()
function categoryIds() {
    $("#categoryId").html('<option value="">全部</option>')
    var datas={}
    if($("#websiteId").val()==""){
        datas={}
    }else {
        datas={
            "websiteId":$("#websiteId").val(),
            "categoryId":"",
        }
    }

    $.ajax({
        type: "POST",
        url: root.brandWebsite.searchCategory,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(datas),
        success: function (data) {
            var levelOnedata=data.data.categoryList
            for (var i=0;i<levelOnedata.length;i++){
                $("#categoryId").append("<option value=" + levelOnedata[i].id + " >" + levelOnedata[i].categoryName + "</option>")
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//客户归属
function myFunction(){
    $.ajax({
        url: root.brandWebsite.searchName,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data:{
            "productName":$("#productName").val(),
        },
        success: function (data) {
            console.log(data)
            if(data.errorCode=="0"){
                var jsonObj =data.data;
                $("#tuank").html("");
                if(jsonObj==""){
                    $("#tuank").html("<li>无数据</li> ");
                }else {
                    var optionstring = "";
                    for (var  i= 0; i < jsonObj.length; i++) {
                        optionstring += "<li class='dda' onclick='relation("+ jsonObj[i].id+",\""+jsonObj[i].productName+"\")' data-align=\"" + jsonObj[i].id + "\" > " + jsonObj[i].productName + "</li>";
                    }
                    $("#tuank").html(optionstring);
                    $(".kehus").animate({scrollTop:"0"},1);
                    $("#tuank").show()

                }
            }else{
                $("#tuank").html("<li>无数据</li> ");
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });


}
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuank").length == 0 && $(e.target).closest("#productName").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuank").hide()
    }
})
function relation(id,ce) {
    $("#productName").val(ce).text(id)
    $("#tuank").hide()
}

/*查询数据*/
function productManagementquery() {
    $.ajax({
        url:root.brandWebsite.queryProductList,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "pageSize":"30",
            "pageNum":"1",
            "websiteId":$("#websiteId").val(),
            "startTime":$("#timemin").val(),
            "endTime":$("#timemax").val(),
            "isRecommend":$("#isRecommend").val(),
            "isPageShow":$("#isPageShow").val(),
            "productName":$("#productName").val(),
            "categoryId":$("#categoryId").val()
        }),
        success: function (data) {
            if(data.errorCode==0){
                homePagelist(data.data, 0);
            }else {
                homePagelist("", 0);
            }
            $('.M-box3').pagination({
                pageCount: data.data.pageCount,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url:root.brandWebsite.queryProductList,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            "pageSize":"30",
                            "pageNum":api.getCurrent(),
                            "websiteId":$("#websiteId").val(),
                            "startTime":$("#timemin").val(),
                            "endTime":$("#timemax").val(),
                            "isRecommend":$("#isRecommend").val(),
                            "isPageShow":$("#isPageShow").val(),
                            "productName":$("#productName").val(),
                            "categoryId":$("#categoryId").val()
                        }),
                        success: function (result) {
                            console.log(result)
                            $("#integralAll")[0].checked = false;
                            homePagelist(result.data);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
/*表格*/
var dataSource = new Array();
//table的数据源
var table;
dataSource = [];
function homePagelist(data, index){
    dataSource.splice(0,dataSource.length);//清空数组
    var datashu =data.startRow+1;
    $.each(data.data, function (i, field) {

        var datashus = datashu++
        var rowData = new Array();
        rowData.push(datashus);
        rowData.push(field.productName);
        rowData.push(field.categoryName);
        rowData.push(field.sedCategoryName);
        rowData.push(field.websiteName);//所属网站
        rowData.push(field.createTime);
        rowData.push(field.isRecommend);
        rowData.push(field.createUser);
        rowData.push(field.id);
        rowData.push(field.isPageShow);

        dataSource.push(rowData);

    });

    initData(dataSource);
    function initData(dataSource) {
        var dttable = $('#productManagementtable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#productManagementtable").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": false,
            "destroy": false,
            "bAutoWidth": false,
            "bLengthChange": false,
            "aLengthMenu":[10,20,30],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span><td><input class="ids"  type="checkbox" onclick="checkItem()"  value = "' + row[8] + '"></td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[5]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = ""
                        if (row[6] == 0) {
                            val = '是'
                        }else {
                            val = '否'
                        }
                        return val;
                    },
                    "targets": 7
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[7]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 8
                },

                {
                    "render": function (data, type, row, meta) {
                        var isRecommend=''//是否推荐
                        var isPageShow=''//是否展示
                        if(row[6]==0){
                            isRecommend='<a onclick="updateProductRecommendStatus(\''+row[8]+'\')">取消推荐</a>'
                        }else {
                            isRecommend='<a onclick="updateProductRecommendStatus(\''+row[8]+'\')">设为推荐</a>'
                        }
                        if(row[9]==0){
                            isPageShow='<a class="ml-10" onclick="updateProductPageShowStatus(\''+row[8]+'\')">取消首页展示</a>'
                        }else {
                            isPageShow='<a class="ml-10" onclick="updateProductPageShowStatus(\''+row[8]+'\')">设为首页展示</a>'
                        }
                        var  val =''+isRecommend+''+isPageShow+'<a class="ml-10" onclick="carouselSettingsdelete(this,\''+row[8]+'\')">删除</a><a class="ml-10" onclick="homePagedetails(\'产品详情\',\'commoditydetail.html\',\''+row[8]+'\')">修改</a>'

                        return val;
                    },
                    "targets":9
                },

            ]
        });
    };
}
/*跳转*/
function homePagedetails(title,url,data,val){
    sessionStorage.setItem("productManagementID",data);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}
//全选
function stopProp() {
    var timer = setTimeout(function() {
        var num = $("#carouselSettingstable").find("tbody").find("input[type=checkbox]:checked").length;
    }, 200)

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}
function checkItem() {
    var checkBoxValues = $("#carouselSettingstable").find("tbody").find("input[type=checkbox]") ;
    if (checkBoxValues && checkBoxValues.length>0){
        var len = 0 ;
        for (var i=0;i<checkBoxValues.length;i++){
            if(checkBoxValues[i].checked){
                len++ ;
            }
        }
        if (len > 0){
            $('#deleteSelected').removeAttr("href");
            $('#deleteSelected').removeAttr("style");

            var isChecked = len == checkBoxValues.length ;
            $("#integralAll")[0].checked = isChecked;
        }else {
            $("#integralAll")[0].checked = false;
        }
    }

}
//多个删除
function carouselSettingsdeletes() {
    var checkBoxValues = $(".shun").find("input[type=checkbox]:checked") ;

        var idListarr=[]
    var idListall={}
    if (checkBoxValues.length>0){
        for (var i=0;i<checkBoxValues.length;i++){
                idListarr.push(checkBoxValues[i].value)

        }
        idListall={
            "list":idListarr
        }


        var cu = layer.confirm('<span>是否要删除已勾选条目</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
            $.ajax({
                url: root.brandWebsite.updateProductDeleteStatus,
                cache: false,  //禁用缓存
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data:JSON.stringify(idListall),
                success: function (data) {
                    if(data.errorCode==0){
                        $.Huimodalalert('删除成功',2000);
                        productManagementquery()
                    }else {
                        $.Huimodalalert(data.msg,2000);
                    }

                },
                error: function () {
                    $.Huimodalalert('失败！',2000);
                }
            });
            layer.close(cu);
        },function(){
            layer.close(cu);

        });

    }else {
        $.Huimodalalert('请选择要删除的条目',2000);
    }
}
//单个删除
function carouselSettingsdelete(dom,val) {
    var checkboxs=$(dom).parent().parent().find('.ids')
    var ids=[]
    ids.push(val)
    var cu = layer.confirm('<span>确定删除吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        $.ajax({
            url: root.brandWebsite.updateProductDeleteStatus,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            contentType: "application/json",
            data:JSON.stringify({
                "list":ids,
                /*"operatorUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,*/
            }),
            success: function (data) {
                if(data.errorCode==0){
                    $.Huimodalalert('删除成功',2000);
                    productManagementquery()
                }else {
                    $.Huimodalalert(data.msg,2000);
                }

            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        });
        layer.close(cu);
    },function(){
        layer.close(cu);

    });
}

//设置推荐
function updateProductRecommendStatus(val) {
    $.ajax({
        url: root.brandWebsite.updateProductRecommendStatus,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data:{
            "id":val,
        },
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('设置成功',2000);
                productManagementquery()
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//设置是否展示
function updateProductPageShowStatus(val) {
    $.ajax({
        url: root.brandWebsite.updateProductPageShowStatus,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data:{
            "id":val,
            /*"operatorUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,*/
        },
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('设置成功',2000);
                productManagementquery()
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

//设置TDK
function setUp() {
    $("#setUp").modal("show");
    $("#websiteId2").html("")
    $.ajax({
        type: "POST",
        url: root.brandWebsite.query,
        cache: false,  //禁用缓存
        dataType: "json",
        async:false,//优先运行
        contentType: "application/json",
        data: JSON.stringify({

        }),
        success: function (data) {
            for (var i=0;i<data.data.data.length;i++){
                $("#websiteId2").append("<option value=" + data.data.data[i].id + " >" + data.data.data[i].websiteName + "</option>")
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
});
    TDKque()

}
//查询TDK
function TDKque() {
    $.ajax({
        type: "post",
        url: root.brandWebsite.queryTDK,
        cache: false,  //禁用缓存
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        dataType: "json",
        data: {
            "type":9,
            "websiteId":$("#websiteId2").val(),
        },
        success: function (data) {
            if(data.data!=null){
                $("#tdkTitle").val(data.data.pageTitle)
                $("#tdkDesc").val(data.data.pageDescription)
                $("#tdkKeyword").val(data.data.pageKeywords)
            }else {
                $("#tdkTitle").val("")
                $("#tdkDesc").val("")
                $("#tdkKeyword").val("")
            }


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//取消
function closeodel() {
    $("#setUp").modal("hide");
}
//保存TDK
function preservationarreall() {
    if( $("#websiteId2").val()=="" || $("#tdkTitle").val()==""|| $("#tdkDesc").val()==""){
        $.Huimodalalert('请填写TDK',2000);
        return false;
    }
    $.ajax({
        type: "POST",
        url: root.brandWebsite.TDKsave,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            "websiteId":$("#websiteId2").val(),
            "msgId":0,
            "pageType":"9",
            "pageTitle":$("#tdkTitle").val(),
            "pageDescription":$("#tdkDesc").val(),
            "pageKeywords":$("#tdkKeyword").val(),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('保存成功',2000);
                $("#setUp").modal("hide");
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}



